package com.nuanshui.heatedloan.service.cms.security;

import com.google.common.collect.Lists;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import com.nuanshui.heatedloan.dao.cms.security.UserVODao;
import com.nuanshui.heatedloan.entity.cms.security.UserVO;
import com.nuanshui.heatedloan.extension.shiro.ShiroDbRealm;
import com.nuanshui.heatedloan.extension.shiro.ShiroDbRealm.HashPassword;
import com.nuanshui.heatedloan.service.cms.BaseService;
import com.nuanshui.heatedloan.service.cms.ServiceException;
import com.nuanshui.heatedloan.util.StorageService;
import com.nuanshui.heatedloan.util.dwz.DwzPage;
import com.nuanshui.heatedloan.util.springdata.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户的管理类
 */
@Service
@Transactional(readOnly = true,value=TransactionManagerType.MANAGER_SERVICE_TRANSACTION_MARGER)
public class ApiUserService extends BaseService<UserVO, Long> {
	private static final Logger logger = LoggerFactory
			.getLogger(ApiUserService.class);

	@Autowired
	private UserVODao userDao;

	@Autowired
	private ShiroDbRealm shiroRealm;


	@Override
	public UserVO get(final Long id) {
		return userDao.findOne(id);
	}

	@Override
	public List<UserVO> findAll(final DwzPage page) {
		final Page<UserVO> page2 = userDao
				.findAll(PageUtils.createPageable(page));
		PageUtils.injectPageProperties(page, page2);
		return page2.getContent();
	}



	/**
	 * 保存用户
	 */
	@Override
	@Transactional(value=TransactionManagerType.MANAGER_SERVICE_TRANSACTION_MARGER)
	public void save(final UserVO user) throws ServiceException {
		if (userDao.findByUsername(user.getUsername()) != null) {
			throw new ServiceException("用户添加失败，登录名：" + user.getUsername()
					+ "已存在。");
		}

		if (userDao.findByRealname(user.getRealname()) != null) {
			throw new ServiceException("用户添加失败，真实名：" + user.getRealname()
					+ "已存在。");
		}

		// 设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash
		if (StringUtils.isNotBlank(user.getPlainPassword())
				&& (shiroRealm != null)) {
			final HashPassword hashPassword = shiroRealm.encrypt(user
					.getPlainPassword());
			user.setSalt(hashPassword.salt);
			user.setPassword(hashPassword.password);
		}
		userDao.save(user);
		shiroRealm.clearCachedAuthorizationInfo(user.getUsername());
	}

	@Override
	@Transactional(value=TransactionManagerType.MANAGER_SERVICE_TRANSACTION_MARGER)
	public void update(final UserVO user) {
		// 设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash
		if (StringUtils.isNotBlank(user.getPlainPassword())
				&& (shiroRealm != null)) {
			final HashPassword hashPassword = shiroRealm.encrypt(user
					.getPlainPassword());
			user.setSalt(hashPassword.salt);
			user.setPassword(hashPassword.password);
			user.setPassword(hashPassword.password);
		}

		userDao.save(user);
	}

	@PersistenceContext
	EntityManager em;

	/**
	 * 修改用户
	 */
	@Transactional(readOnly = false,value=TransactionManagerType.MANAGER_SERVICE_TRANSACTION_MARGER)
	public void update(final UserVO user, final MultipartFile photos) {
		// 设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash
		if (StringUtils.isNotBlank(user.getPlainPassword())
				&& (shiroRealm != null)) {
			final HashPassword hashPassword = shiroRealm.encrypt(user
					.getPlainPassword());
			user.setSalt(hashPassword.salt);
			user.setPassword(hashPassword.password);
		}
		// 文件上传处理
		if (!photos.isEmpty()) {
			try {
				final String path = StorageService.IMAGES.save(photos);
				user.setPhoto(path);
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
		em.clear();
		userDao.save(user);
		shiroRealm.clearCachedAuthorizationInfo(user.getUsername());
	}

	/**
	 * 删除用户
	 */
	@Override
	@Transactional(value=TransactionManagerType.MANAGER_SERVICE_TRANSACTION_MARGER)
	public void delete(final Long id) throws ServiceException {
		if (isSupervisor(id)) {
			logger.warn("操作员{}，尝试删除超级管理员用户", SecurityUtils.getSubject()
					.getPrincipal() + "。");
			throw new ServiceException("不能删除超级管理员用户。");
		}
		userDao.delete(id);
	}

	/**
	 * 根据名称拿到一个用户
	 */
	public UserVO get(final String username) {
		return userDao.findByUsername(username);
	}

	/**
	 * 分页
	 */
	public List<UserVO> find(final DwzPage page, final String name) {
		final org.springframework.data.domain.Page<UserVO> pageUser = userDao
				.findByUsernameContaining(name, PageUtils.createPageable(page));
		PageUtils.injectPageProperties(page, pageUser);
		return pageUser.getContent();
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(final Long id) {
		return id == 1;
	}

	/**
	 * 删除用户
	 * @param id
	 */
	public void deleteById(Long id) {
		//usersDaoImpl.deleteUserById(id);
	}

	public List<String> findPermissionsByRoleId(Long id) {
	    List<String> permissions = Lists.newArrayList();
		return permissions;
		
	}

}
